<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Str;
use App\Format\Format;

class SetFotmatMethods extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'set:format-methods {format}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'set fotmat method note';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $formatName = $this->argument('format');
        $className = Str::camel($formatName) . 'Format';
        /* @var $class Format */
        $fillName = sprintf('App\\Format\\%s', $className);
        $class = new $fillName;
        $allProtesteds = $class->getAllProtected();
        $methods = $this->getMethods($allProtesteds);
        $this->fillMethods($methods);
        $notesStr = implode(PHP_EOL, $methods) . PHP_EOL;
        $classFile = $this->readFile($className);
        $p = '/<?php([\w\W]*)class/i';
        preg_match_all($p, $classFile, $match);
        $newFile = str_replace($match[1][0], $notesStr, $classFile);

        $this->rewriteFormat($className, $newFile);
        $this->info('set success');
        return 0;
    }

    private function getMethods(array $pros)
    {
        $res = [];
        // getter
        foreach ($pros as $key => $pro) {
            array_push($res, '* @method ' . Str::camel('get_' . $pro . '()'));
        }

        array_push($res, '*');

        // setter
        foreach ($pros as $key => $pro) {
            array_push($res, '* @method ' . Str::camel('set_' . $pro . '($value)'));
        }

        return $res;
    }

    private function fillMethods(&$methods)
    {
        array_push($methods, '*');
        array_push($methods, '*/');

        array_unshift($methods, '*');
        array_unshift($methods, '/**');
        array_unshift($methods, PHP_EOL);
        array_unshift($methods, 'namespace App\Format;');
        array_unshift($methods, PHP_EOL);
    }

    private function readFile($className)
    {
        $fileName = $this->getFormatClassPath() . '/' . $className . '.php';
        $file = fopen($fileName, 'a+');
        $content = fread($file, filesize($fileName));
        fclose($file);
        return $content;
    }

    private function rewriteFormat($className, $newFile)
    {
        $fileName = $this->getFormatClassPath() . '/' . $className . '.php';
        $file = fopen($fileName, 'w+');
        fwrite($file, $newFile);
    }

    private function getFormatClassPath()
    {
        return base_path() . '/app/Format';
    }
}
